<template>
    <div id="prizeCenter" class="clearfix">
        <!-- 数据筛选条件选择 -->
        <div>
            <el-row :gutter="20" class="clearfix">
                <el-col :span="6">
                    <div class="pull-left mr10 lh34 c888 fs12">切换活动</div>
                    <el-select v-model="activityId" placeholder="请选择" size="small" @change="search">
                        <el-option
                        v-for="item in activityList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="6">
                    <el-date-picker
                        size="small"
                        v-model="dateScope"
                        type="daterange"
                        align="right"
                        placeholder="选择日期范围"
                        :editable="false"
                        :picker-options="pickerOptions"
                        @change="search">
                    </el-date-picker>
                </el-col>
                <el-col :span="4">
                    <el-input placeholder="领奖手机号" v-model="phoneNumber" size="small">
                        <el-button class="el-button-search" slot="append" icon="search" @click="search"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="3">
                    <el-select v-model="screen" placeholder="批量筛选" size="small"  @change="search">
                        <el-option
                        v-for="item in prizeStateList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </el-col>
                <!-- <el-col :span="4">
                    <el-button type="danger" size="small" class="pull-right el-button-downloadTable"  @click="downloadTable">下载表格</el-button>
                </el-col> -->
            </el-row>
        </div>
        <!-- 中奖数据 -->
        <div class="table-div"  v-loading="loadingChoose">
             <el-table
                :data="tableData"
                stripe
                style="width: 100%"
                @filter-change="filterChange">
                <el-table-column
                    prop="created_at"
                    label="中奖时间"
                    align="center">
                </el-table-column>
                <el-table-column
                    label="奖品"
                    align="center"
                    @header-click="filterChange">
                    <template slot-scope="scope">
                        <div slot="reference" class="name-wrapper">
                           {{scope.row.prize_name == '' ? '未知' : scope.row.prize_name}}
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column
                    prop="tag"
                    label="所有奖品"
                    width="180"
                    align="center"
                    :filters="allPrize"
                    :filter-method="filterTag"
                    filter-placement="bottom-end">
                    <template slot-scope="scope">
                        <el-tag
                        :type="scope.row.tag === '家' ? 'primary' : 'success'"
                        close-transition>{{scope.row.tag}}</el-tag>
                    </template>
                </el-table-column> -->
                <el-table-column
                    label="类型"
                    align="center">
                    <template slot-scope="scope">
                        <div slot="reference" class="name-wrapper">
                           {{scope.row.type_code == 'coupon' ? '优惠券' : scope.row.type_code =='redpack' ? '红包': scope.row.type_code =='entity' ? '实物': '未知'}}
                        </div>
                    </template>
                </el-table-column>
                
                <el-table-column
                    label="中奖者"
                    align="center">
                    <template slot-scope="scope">
                        <div slot="reference" class="name-wrapper">
                           <ul class="prizeName">
                               <li><img class="avatarImg" :src="scope.row.avatar == '' ? require('../assets/img/avatar.jpg') : scope.row.avatar"><span class="nickname">{{scope.row.nickname == '' ? '匿名' : scope.row.nickname}}</span></li>
                               <li>
                                   <el-tooltip class="item" effect="dark" content="OpenId" placement="left">
                                       <span>{{scope.row.openid}}</span>
                                   </el-tooltip>
                                </li>
                           </ul>
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column
                    prop=""
                    label="中奖状态"
                    align="center">
                </el-table-column> -->
                <el-table-column
                    label="中奖状态"
                    align="center">
                    <template slot-scope="scope">   
                        <div slot="reference" class="name-wrapper">
                            <el-tag
                            :type="scope.row.is_exchange === 0 ? 'primary' : scope.row.is_exchange == 1 ? 'success' : scope.row.is_exchange==2 ? 'warning' : ''"
                            close-transition>{{scope.row.is_exchange==0 ? '未兑奖' : scope.row.is_exchange==1 ? '已兑换' : scope.row.is_exchange==2 ? '提交中' : '兑奖失败'}}</el-tag>
                        </div>    
                    </template>
                </el-table-column>
                
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button
                        class="el-button-inventory"
                        size="mini"
                        type="info"
                        @click="showfillForm(scope.$index, scope.row)"
                        >查看信息</el-button>
                        <!-- <el-button
                        class="el-button-inventory"
                        size="mini"
                        type="warning"
                        @click="showfillForm(scope.$index, scope.row)"
                        v-else-if="scope.row.is_exchange != 0">填写表单</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <div class='pagination'>
            <!-- 
                size-change	pageSize 改变时会触发
                current-change	currentPage 改变时会触发

                page-size	每页显示条目个数
                total	总条目数
                current-page	当前页数，
                layout	组件布局，子组件名用逗号分隔
             -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage"
                :page-size="pageSize"
                layout="prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <!-- 下载提示框 -->
        <!-- <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            size="tiny"
            :before-close="handleClose">
            <span>该活动没有中奖记录</span>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog> -->

        <!-- 查看信息提示框 -->
        <el-dialog title="用户信息" :visible.sync="dialogVisibleInfo">
            <el-table :data="gridData">
                <el-table-column property="name" label="收件人" width="150" align='center'></el-table-column>
                <el-table-column property="mobile" label="联系电话" width="200" align='center'></el-table-column>
                <el-table-column property="address" label="收货地址" align='center'></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleInfo = false">取 消</el-button>
                <el-button v-if="editStatus==2" type="primary" @click="submitUserInfo()">确认信息</el-button>
                <el-button v-show="editStatus==0||editStatus==2" type="warning" @click="failure()">兑奖失败</el-button>                
            </div>
        </el-dialog>
    </div>
</template>

<script>
import * as api from "./../api/api";
export default {
  data() {
    return {
      loadingChoose:false,  //加载中      
      activityList: [], //活动列表
      activityId:'',//选中的活动id
      //日期范围
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setHours(23);
              end.setMinutes(59);
              end.setSeconds(59);
              end.setMilliseconds(999);
              start.setHours(0);
              start.setMinutes(0);
              start.setSeconds(0);
              start.setMilliseconds(0);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
              end.setHours(23);
              end.setMinutes(59);
              end.setSeconds(59);
              end.setMilliseconds(999);
              start.setHours(0);
              start.setMinutes(0);
              start.setSeconds(0);
              start.setMilliseconds(0);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "过去7天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              end.setHours(23);
              end.setMinutes(59);
              end.setSeconds(59);
              end.setMilliseconds(999);
              start.setHours(0);
              start.setMinutes(0);
              start.setSeconds(0);
              start.setMilliseconds(0);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "过去30天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              end.setHours(23);
              end.setMinutes(59);
              end.setSeconds(59);
              end.setMilliseconds(999);
              start.setHours(0);
              start.setMinutes(0);
              start.setSeconds(0);
              start.setMilliseconds(0);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      dateScope: '',//选中的时间范围
      phoneNumber:'',//电话号码
      prizeStateList:[{
          value:'全部',
          lable:'全部'
      },{
          value:'未兑奖',
          lable:'未兑奖'
      },{
          value:'已兑奖',
          lable:'已兑奖'
      },{
          value:'提交中',
          lable:'提交中'
      },{
          value:'兑奖失败',
          lable:'兑奖失败'
      }],
      screen:'',//批量筛选
      allPrize:[{ text: '家', value: '家' }, { text: '公司', value: '公司' }],//所有奖品
      allType:[],//所有类型
      allState:[],//所有状态
      allData:[],//所有中奖数据
      newData:[],//筛选过后的数据
      tableData: [],//显示的中奖数据
      pageSize:15,//每页显示条数
      total: 0,//总条数
      currentPage: 1,//默认页码
      dialogVisible: false, //显示/隐藏下载提示框
      dialogVisibleInfo: false,//显示/隐藏查看信息提示框
      gridData: [],//查看信息提示框数据
      editId:'',//当前中奖信息的id
      editStatus:'',//当前中奖信息的状态
    };
  },
  mounted() {
      this.fetchPrizeList();
      this.fetchActivityList();
  },
  computed: {},
  methods: {
      //获取中奖列表
      fetchPrizeList() {
          let vm = this;
          vm.loadingChoose=true;
          api.prizeCenter().then(res => {
            res.data.data=res.data.data.sort(function(a,b){return Date.parse(b.created_at) - Date.parse(a.created_at)});
            vm.pagination(res.data.data);
            vm.allData = res.data.data;
            vm.loadingChoose=false;
          }).catch(err=>{
          })
      },
      //获取活动列表
      fetchActivityList(){
            let vm = this;
            // vm.loading = true;
            let body={
                search:'', //搜索
                category: '2',
                order: 'aesc',
                limit: 100000,
                offset: 0,
                soft:''
            };
            api.activityList(body).then(res => {
               vm.activityList = res.data.data.rows;
               vm.activityList.unshift({'name':'所有活动','id':'0'});
            }).catch(err=>{
                vm.httpStatusCode(err);
            })    
        },
      //筛选
      search(){
        let activityId;
        let dateScope;
        let phoneNumber;
        let screen;
        let newData=this.allData;
        //按活动名筛选
        if(this.activityId != ''){
            if(this.activityId != '0'){
                activityId = this.activityId;
                let arr = [];
                for(let i=0;i<newData.length;i++){
                    if(newData[i].activity_id==activityId){
                        arr.push(newData[i]);
                    }
                }
                newData = arr;
            }
        };
        //按日期筛选
        if(this.dateScope != ''){ 
            dateScope = this.dateScope; 
            console.log(dateScope);
            if(dateScope[0]==null||dateScope[1]==null){
                newData = newData;
            }else{
                let arr = [];
                dateScope[1]=new Date(this.getNowFormatDate(dateScope[1])+' '+'23:59:59');  
                for(let i=0;i<newData.length;i++){ 
                    if((Date.parse(newData[i].created_at)/1000 > Date.parse(dateScope[0])/1000) && (Date.parse(newData[i].created_at)/1000 < Date.parse(dateScope[1])/1000 )){ 
                        arr.push(newData[i]);
                    }
                } 
                newData = arr;
            }  
        };
        //按手机号筛选
        if(this.phoneNumber != ''){
            phoneNumber = this.phoneNumber;
            // newData.filter(function(x){
            //     return x.mobile == phoneNumber;
            // })
            let arr = [];
            for(let i=0;i<newData.length;i++){
                if(newData[i].mobile==phoneNumber){
                    arr.push(newData[i]);
                }
            }
            newData = arr;
            
        };
        //按状态筛选
        if(this.screen != '' && this.screen != '全部'){
            if(this.screen == '未兑奖'){
                screen = '0';
            }else if(this.screen == '已兑奖'){
                screen = '1';
            }else if(this.screen == '提交中'){
                screen = '2';
            }else {
                screen = '3'
            };
            let arr=[];
            for(let i=0;i<newData.length;i++){
                if(newData[i].is_exchange==screen){
                    arr.push(newData[i]);
                }
            }
            newData = arr;
            
        };
        this.newData = newData;
        this.pagination(newData);
        this.currentPage = 1;
      },
      getNowFormatDate (date) { 
            let seperator1 = "-";
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            let currentdate = year + seperator1 + month + seperator1 + strDate;
            return currentdate;
        },
      //下载表格
      downloadTable() {
          if(this.tableData.length===0){
              this.dialogVisible=true;
          }else {
              
          }
      },
      //释放库存
      inventoryDelete(index,row) {
        //   console.log('index',index,'row',row)
      },
      //用户信息弹框
      showfillForm(index, row){
          if(row.name==''){
              row.name='未知'
          }
          if(row.address==''){
              row.address='未知'
          }
          if(row.mobile==''){
              row.mobile='0'
          }
          this.gridData = [];
          this.gridData.push(row);
          this.editId = row.id;
          this.editStatus = row.is_exchange;
          this.dialogVisibleInfo = true;
          console.log(this.editStatus)
      },

      //提交用户兑奖信息
      submitUserInfo(){
          let status = {status : 1};
          let id = this.editId;
          api.submitUserInfo(id,status).then(res => {
              if(res.data.code == 200){
                  this.dialogVisibleInfo = false
                  this.$message({showClose: true,message: '提交成功！'});
                  this.fetchPrizeList();
              }else{
                  this.$message({showClose: true,message: '提交失败！'})
                  this.dialogVisibleInfo = false;                  
              }
          })
      },

      //兑奖失败提交
      failure(){
          let status = {status : 3};
          let id = this.editId;
          api.submitUserInfo(id,status).then(res => {
              if(res.data.code == 200){
                  this.dialogVisibleInfo = false;
                  this.$message({showClose: true,message: '提交成功！'});
                  this.fetchPrizeList();
              }else{
                  this.$message({showClose: true,message: '提交失败！'})
                  this.dialogVisibleInfo = false;                  
              }
          })
      },

      //分页效果
      pagination(data){
          this.total = data.length;
          if(data.length <= this.pageSize){
              this.tableData = data;             
          }else{
              this.tableData = data.slice(0,this.pageSize);
          }
      },
      //每页显示条数改变
      handleSizeChange(val) {
        // console.log(`每页 ${val} 条`);
      },
      //当前页改变
      handleCurrentChange(val) {
        if(this.newData.length != 0){
            this.tableData = this.newData.slice((val-1)*this.pageSize,val*this.pageSize);
        }else{
            this.tableData = this.allData.slice((val-1)*this.pageSize,val*this.pageSize);            
        }
      },
      //关闭提示框
      handleClose(done) {
          this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      filterChange(filters) {
        //   console.log(filters)
      },
      filterTag(value, row) {
        return row.tag === value;
      }
  }
};
</script>

<style lang="less">
@import "../style/common";
#prizeCenter {
  min-width: 960px;
  height: 100%;
//   overflow-x: hidden;
  padding: 40px;
  .lh34 {
    line-height: 34px;
  }
  .mr10 {
    margin-right: 10px;
  }
  .c888 {
    color: #888;
  }
  .fs12 {
    font-size: 12px;
  }
  .el-select {
    width: 128px;
    height: 34px;
  }
  .el-input--small .el-input__inner {
    height: 34px;
  }
  .el-button{
      height: 34px;
  }
  .el-table{
      margin-top: 20px;
  }
  .el-button-inventory{
      height: 34px;
      width: 70%
  }
  .el-table__row{
      padding:10px 0;
  }
  .pagination{
      width: 50%;
      margin: 20px auto;
      text-align: center;
  }
  .el-button-downloadTable{
      width: 90px;
      height: 30px;
      margin-top: 4px;
      border-radius: 24px;
  }
  .prizeName{
      font-size: 12px;
      color: #888;
      text-align: left;
      padding-top: 4px;
      .nickname{
          line-height: 30px;
          vertical-align: 10px;
          margin-left: 8px;
      }
  }
  .avatarImg{
      width: 30px;
      height: 30px;
  }
}
</style>
